<?php

/**
 *    文章管理控制器
 *
 *    @author    Hyber
 *    @usage    none
 */
class CourseApp extends BackendApp
{
	var $_course_mod;
	var $_uploadedfile_mod;

	function __construct()
	{
		$this->CourseApp();
	}

	function CourseApp()
	{
		parent::BackendApp();

		$this->_course_mod =& m('course');
		$this->_uploadedfile_mod = &m('uploadedfile');
	}

	/**
	 *    文章索引
	 *
	 *    @author    Hyber
	 *    @return    void
	 */
	function index()
	{
			
		$conditions='';
		$conditions .= $this->_get_query_conditions(array(
		array(
                'field' => 'title',         //可搜索字段title
                'equal' => 'LIKE',          //等价关系,可以是LIKE, =, <, >, <>
                'assoc' => 'AND',           //关系类型,可以是AND, OR
                'name'  => 'title',         //GET的值的访问键名
                'type'  => 'string',        //GET的值的类型
		),
		array(
                'field' => 'name',         //可搜索字段title
                'equal' => 'LIKE',          //等价关系,可以是LIKE, =, <, >, <>
                'assoc' => 'or',           //关系类型,可以是AND, OR
                'name'  => 'title',         //GET的值的访问键名
                'type'  => 'string',        //GET的值的类型
		),
		array(
                'field' => 'cate',  
		        'equal' => 'LIKE',               
                'assoc' => 'AND',
                'name' => 'cate',
                'type' => 'string',
		),
		));
		$page   =   $this->_get_page(10);   //获取分页信息


			

		$sql="SELECT  cc.*,cm.user_id,cm.real_name,cm.user_name from   cw_course cc
LEFT JOIN  cw_member cm on cc.uid=cm.user_id	
WHERE 1=1 $conditions ORDER BY course_id DESC limit $page[limit]";
		$articles=$this->_course_mod->db->getAll($sql);

		$sql="SELECT  count(1) FROM cw_course cc
LEFT JOIN  cw_member cm on cc.uid=cm.user_id	
WHERE 1=1 ".$conditions;
		$count=$this->_course_mod->db->getOne($sql);
		$page['item_count']=$count;   //获取统计数据


		$sql="select  * from   cw_dictionary where  d_code='course'";//
	 $dis_list = $this->_course_mod->GetAll($sql);
	 $dis_cat=array();
	 foreach ($dis_list as $k=>$v){
	 	$dis_cat[$v['d_key']]=$v['d_value'];
	 }
	 $this->assign('dis_cat', $dis_cat);
	 //	$page['item_count']=$this->_course_mod->getCount();   //获取统计数据
		$this->_format_page($page);
		$this->import_resource(array('script' => 'inline_edit.js'));
		$this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
		$this->assign('page_info', $page);   //将分页信息传递给视图，用于形成分页条
		$this->assign('articles', $articles);
		$this->display('course.index.html');
	}
	/**
	 *    新增文章
	 *
	 *    @author    Hyber
	 *    @return    void
	 */
	function add()
	{
		if (!IS_POST)
		{
			/* 显示新增表单 */
			$course = array('sort_order' => 255,'number'=>0,'validityday'=>0,);
			$this->assign('course', $course);
			$sql="select  * from   cw_dictionary where  d_code='course'";//
			$dis_list = $this->_course_mod->GetAll($sql);
			$dis_cat=array();
			foreach ($dis_list as $k=>$v){
				$dis_cat[$v['d_key']]=$v['d_value'];
			}
			//$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js,inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
			/*
			 $h=array();
			 for($i=0;$i<24;$i++){
				$h[$i]=$i.'点';
				}
				$this->assign('h', $h);

				$s=array();
				for($i=0;$i<60;$i++){
				$s[$i]=$i.'分';
				}
				$this->assign('s', $s);
				*/
			$this->assign('dis_cat', $dis_cat);
			$this->display('course.form.html');
		}
		else
		{
			/*
			 $hourstart = !isset($_POST['hourstart']) ? -1 : intval($_POST['hourstart']);
			 $hourend = !isset($_POST['hourend']) ? 0 : intval($_POST['hourend']);
			 $hourstartm = !isset($_POST['hourstartm']) ? -1 : intval($_POST['hourstartm']);
			 $hourendm = !isset($_POST['hourendm']) ? 0 : intval($_POST['hourendm']);
			 if($hourstart<0){
				$hourstartm=-1;
				}else{
				if($hourstartm<0){
				$hourstartm=0;
				}
				}
				if($hourend<0){
				$hourendm=-1;
				}else{
				if($hourendm<0){
				$hourendm=0;
				}
				}
				$hourstart=$hourstart*60+$hourstartm;
				$hourend=$hourend*60+$hourendm;
				if($hourend>=0){
				if($hourend<=$hourstart){
				$this->show_warning('时间后者大于前者');
				return;
				}
				}*/

			if((!empty($_POST['validitystart'])&&empty($_POST['validity']))||(empty($_POST['validitystart'])&&!empty($_POST['validity'])) ){
				$this->show_warning('上课时间必须两个都选');
				return;
			}



			$data = array();
			$data['title']      =   $_POST['title'];
			$data['name']      =   $_POST['name'];
			$data['cate']    =   $_POST['cate'];
			$data['price']    =   $_POST['price'];
			$data['old_price']    =   $_POST['old_price'];
			$data['lessons']    =   $_POST['lessons'];
			$data['validityday']    =   $_POST['validityday'];
			$data['validity']    =  strtotime($_POST['validity']);
			$data['validitystart']    =  strtotime($_POST['validitystart']);
			$data['fit']    =   $_POST['fit'];
			$data['description']    =   $_POST['description'];
			$data['tags']    =   $_POST['tags'];
			$data['outline']    =   $_POST['outline'];
			$data['number']    =   $_POST['number'];
			//	$data['take_time_start']    = $hourstart;
			//	$data['take_time_end']    =   $hourend;
			$data['isopen'] =   $_POST['isopen'];
			$data['sort_order'] =   $_POST['sort_order'];
			$data['add_time'] =  gmtime();
			$data['uid']=$this->visitor->get('user_id');
			if (!$article_id = $this->_course_mod->add($data))  //获取article_id
			{
				$this->show_warning($this->_course_mod->get_error());

				return;
			}

			/* 处理上传的图片 */
			$logo       =   $this->_upload_logo($article_id);
			if ($logo === false)
			{
				return;
			}
			$logo && $this->_course_mod->edit($article_id, array('pic' => $logo)); //将logo地址记下

			$this->show_message('add_activity_successed',
                'back_list',    'index.php?app=course',
                'continue_add', 'index.php?app=course&amp;act=add'
                );
		}
	}
	/**
	 *    编辑文章
	 *
	 *    @author    Hyber
	 *    @return    void
	 */
	function edit()
	{
		$article_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
		if (!$article_id)
		{
			$this->show_warning('no_such_activity');
			return;
		}
		if (!IS_POST)
		{
			$activity     = $this->_course_mod->find($article_id);
			/*
			 $h=array();
			 for($i=0;$i<24;$i++){
				$h[$i]=$i.'点';
				}
				$this->assign('h', $h);

				$s=array();
				for($i=0;$i<60;$i++){
				$s[$i]=$i.'分';
				}
				$this->assign('s', $s);
				*/
			if (empty($activity))
			{
				$this->show_warning('no_such_activity');
				return;
			}

			$sql="select  * from   cw_dictionary where  d_code='course'";//
			$dis_list = $this->_course_mod->GetAll($sql);
			$dis_cat=array();
			foreach ($dis_list as $k=>$v){
				$dis_cat[$v['d_key']]=$v['d_value'];
			}
			$this->assign('dis_cat', $dis_cat);
			//$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
			$this->import_resource(array('script' => 'mlselection.js,jquery.plugins/jquery.validate.js,change_upload.js,inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));

			$activity    =   current($activity);
			/*
			 if($activity['take_time_start']){

				$activity['hourstartm']=intval($activity['take_time_start'])%60;

				$activity['hourstart']=intval($activity['take_time_start']/60);
				}
				if($activity['take_time_end']){
				$activity['hourendm']=$activity['take_time_end']%60;

				$activity['hourend']=intval($activity['take_time_end']/60);
				}
				if($activity['uid']){

				$sql="SELECT  cc.*,cm.user_id,cm.user_name from   cw_course cc
				LEFT JOIN  cw_member cm on cc.uid=cm.user_id
				WHERE   course_id=".$article_id;
				$articles=$this->_course_mod->db->getRow($sql);
				$activity['user_name']= $articles['user_name'];
				$activity['user_id']= $articles['user_id'];
				}
				*/

			if($activity['validity']){
				$activity['validity']=date("Y-m-d",$activity['validity']);
			}
			if($activity['validitystart']){
				$activity['validitystart']=date("Y-m-d",$activity['validitystart']);
			}
			$sql="SELECT  count(1) from  cw_courseorder ccr
LEFT JOIN   cw_course cc  on ccr.course_id=cc.course_id
where  cc.course_id=$article_id and  ccr.`status`='已支付'";
			if($this->_course_mod->GetOne($sql)){
				//$activity['noedit']=1;
			}else{
				//$activity['noedit']=0;
			}

			$this->assign('course', $activity);



			$pageSize=10;//每页显示的记录数
			if(isset($_GET['page'])){
				$page=intval($_GET['page']);
			}else{
				$page=1;
			}
			$offset=$pageSize*($page-1);//卷滚的记录条数



			$sql="select  * from  cw_coursetime where course_id=".$article_id." order by  take_date ,lessons  ,take_time_start desc LIMIT $offset,$pageSize ";
			$list = $this->_course_mod->GetAll($sql);
			$coursetime_list=array();
			foreach ($list as $k=>$v){
				if($v['take_time_start']){
			 	$v['hourstartm']=intval($v['take_time_start'])%60;
			 	$v['hourstart']=intval($v['take_time_start']/60);
				}

				if($v['take_time_end']){
					$v['hourendm']=$v['take_time_end']%60;
					$v['hourend']=intval($v['take_time_end']/60);
				}
				$v['take_date']=date('y-m-d',$v['take_date']);
				$coursetime_list[]=$v;
			}

			$sql_all="select  count(1) from  cw_coursetime where course_id=".$article_id;
			$rowNum= $this->_course_mod->getOne($sql_all);
			$pages=ceil($rowNum/$pageSize);//总页数
			$first=1;
			$last=$pages;
			if($page==1){
				$prev=1;
			}else{
				$prev=$page-1;
			}
			if($page==$pages){
				$next=$pages;
			}else{
				$next=$page+1;
			}
			$app=$_REQUEST['app'];
			$act=$_REQUEST['act'];
			$fenye=<<<EOD
<div class="pageLinks">
<div class="page mtr10">
<a class="stat">$page/$pages 页 (共 $rowNum 条)</a> 
  <span class="formerNull"></span>
  <a class="page_link" href="index.php?app=$app&act=$act&id=$article_id&page=$first">&lt;&lt;第一页</a>
  <a class="page_link" href="index.php?app=$app&act=$act&id=$article_id&page=$prev">&lt;上一页</a>
  <a class="page_link" href="index.php?app=$app&act=$act&id=$article_id&page=$next">下一页&gt;</a>
  <a class="page_link" href="index.php?app=$app&act=$act&id=$article_id&page=$last">最后一页&gt;&gt;</a>
 </div>
</div>
EOD;

			$this->assign('coursetime_list', $coursetime_list);
			$this->assign('fenye', $fenye);


			$sql="select  * from  cw_coursefile where course_id=".$article_id." order by sort_order";
			$list = $this->_course_mod->GetAll($sql);
			$coursefile_list=array();
			foreach ($list as $k=>$v){
				if($v['add_time']){
					$v['add_time']=date('y-m-d H:s:m',$v['add_time']);
				}

				$coursefile_list[]=$v;
			}
			$this->assign('coursefile_list', $coursefile_list);
			$this->display('course.form.html');
		}
		else
		{
			/*
			 $hourstart = !isset($_POST['hourstart']) ? -1 : intval($_POST['hourstart']);
			 $hourend = !isset($_POST['hourend']) ? 0 : intval($_POST['hourend']);
			 $hourstartm = !isset($_POST['hourstartm']) ? -1 : intval($_POST['hourstartm']);
			 $hourendm = !isset($_POST['hourendm']) ? 0 : intval($_POST['hourendm']);
			 if($hourstart<0){
			 $hourstartm=-1;
			 }else{
			 if($hourstartm<0){
			 $hourstartm=0;
			 }
			 }
			 if($hourend<0){
			 $hourendm=-1;
			 }else{
			 if($hourendm<0){
			 $hourendm=0;
			 }
			 }

			 $hourstart=$hourstart*60+$hourstartm;
			 $hourend=$hourend*60+$hourendm;
			 if($hourend>=0){
			 if($hourend<=$hourstart){
			 //$this->show_warning('时间后者大于前者');
			 //return;
			 }
			 }
			 */
			if((!empty($_POST['validitystart'])&&empty($_POST['validity']))||(empty($_POST['validitystart'])&&!empty($_POST['validity'])) ){
				$this->show_warning('上课时间必须两个都选');
				return;
			}
			$data = array();
			$data['title']      =   $_POST['title'];
			$data['name']      =   $_POST['name'];
			$data['cate']    =   $_POST['cate'];
			$data['price']    =   $_POST['price'];
			$data['old_price']    =   $_POST['old_price'];
			$data['lessons']    =   $_POST['lessons'];
			$data['validityday']    =   $_POST['validityday'];
			$data['validity']    =    strtotime($_POST['validity']);
			$data['validitystart']    =  strtotime($_POST['validitystart']);
			$data['fit']    =   $_POST['fit'];
			$data['description']    =   $_POST['description'];
			$data['tags']    =   $_POST['tags'];
			$data['outline']    =   $_POST['outline'];
			$data['number']    =   $_POST['number'];
			//$data['take_time_start']    = $hourstart;
			//$data['take_time_end']    =   $hourend;
			$data['isopen'] =   $_POST['isopen'];
			$data['sort_order'] =   $_POST['sort_order'];
			$data['add_time'] =  gmtime();
			$data['uid']=$this->visitor->get('user_id');

			$rows=$this->_course_mod->edit($article_id, $data);
			if ($this->_course_mod->has_error())
			{
				$this->show_warning($this->_course_mod->get_error());

				return;
			}

			/* 处理上传的图片 */
			$logo       =   $this->_upload_logo($article_id);
			if ($logo === false)
			{
				return;
			}
			$logo && $this->_course_mod->edit($article_id, array('pic' => $logo)); //将logo地址记下

			$this->show_message('edit_activity_successed',
                'back_list',        'index.php?app=course',
                'edit_again',    'index.php?app=course&amp;act=edit&amp;id=' . $article_id);
		}
	}

	//异步修改数据
	function ajax_col()
	{
		$id     = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$column = empty($_GET['column']) ? '' : trim($_GET['column']);
		$value  = isset($_GET['value']) ? trim($_GET['value']) : '';
		$data   = array();

		if (in_array($column ,array('isopen', 'sort_order','filesort_order')))
		{
			if($column=='filesort_order'){//修改 cw_coursefile
				$sql=" update  cw_coursefile set sort_order='$value' where file_id=".$id;
				$this->_course_mod->db->Query($sql);
			}else{
				$data[$column] = $value;
				$this->_course_mod->edit($id, $data);
				if(!$this->_course_mod->has_error())
				{
					echo ecm_json_encode(true);
				}
			}
		}
		else
		{
			return ;
		}
		return ;
	}
	function drop()
	{
		$article_ids = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$article_ids)
		{
			$this->show_warning('no_such_activity');

			return;
		}
		$article_ids=explode(',', $article_ids);
		$this->_course_mod->drop($article_ids);
		if ($this->_course_mod->has_error())    //删除
		{
			$this->show_warning($this->_course_mod->get_error());

			return;
		}

		$this->show_message('drop_ok');
	}



	/* 更新排序 */
	function update_order()
	{
		if (empty($_GET['id']))
		{
			$this->show_warning('Hacking Attempt');
			return;
		}
		$ids = explode(',', $_GET['id']);
		$sort_orders = explode(',', $_GET['sort_order']);
		foreach ($ids as $key => $id)
		{
			$this->_article_mod->edit($id, array('sort_order' => $sort_orders[$key]));
		}

		$this->show_message('update_order_ok');
	}

	//添加课程 课时
	function   timeadd(){
		$id=$_REQUEST['id'];
		if (!IS_POST)
		{
			$h=array();
			for($i=0;$i<24;$i++){
				$h[$i]=$i.'点';
			}
			$this->assign('h', $h);

			$s=array();
			for($i=0;$i<60;$i++){
				$s[$i]=$i.'分';
			}
			$lessonslist=array();
			for($i=1;$i<=4;$i++){
				$lessonslist[$i]=$i.'课时';
			}

			$this->assign('lessonslist', $lessonslist);
			$this->assign('s', $s);
			//$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js,inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
			$this->display('coursetime.form.html');
		}else{

			$hourstart = !isset($_POST['hourstart']) ? -1 : intval($_POST['hourstart']);
			$hourend = !isset($_POST['hourend']) ? 0 : intval($_POST['hourend']);
			$hourstartm = !isset($_POST['hourstartm']) ? -1 : intval($_POST['hourstartm']);
			$hourendm = !isset($_POST['hourendm']) ? 0 : intval($_POST['hourendm']);
			if($hourstart<0){
				$hourstartm=-1;
			}else{
				if($hourstartm<0){
					$hourstartm=0;
				}
			}
			if($hourend<0){
				$hourendm=-1;
			}else{
				if($hourendm<0){
					$hourendm=0;
				}
			}

			$hourstart=$hourstart*60+$hourstartm;
			$hourend=$hourend*60+$hourendm;
			if($hourend>=0){
				if($hourend<=$hourstart){
					$this->show_warning('时间后者大于前者');
					return;
				}
			}
			$lessons=!isset($_POST['lessons']) ? 0 : intval($_POST['lessons']);
			$note=!isset($_POST['note']) ? '' : intval($_POST['note']);
			$take_date= strtotime($_POST['take_date']);
			$sql="insert into cw_coursetime(lessons,take_time_start,take_time_end,course_id,take_date,note) values('$lessons','$hourstart','$hourend','$id','$take_date','$note')";
			$this->_course_mod->db->Query($sql);
			//更新课程的课时
			if($id){
				$sql="select  *  from  cw_course where  course_id=".$id;
				$course=$this->_course_mod->db->GetRow($sql);
				$diff=$course['validity']-$course['validitystart'];
				$days=  $diff/(24*60*60)+1;
				$sql="select  sum(lessons)  from  cw_coursetime where  course_id=".$id;
				$lessons=$course=$this->_course_mod->db->Getone($sql);//查询总的课时
				$ls=$days*$lessons;
				$sql="update  cw_course  set lessons='$ls' where  course_id=".$id;//更新课程课时
				$this->_course_mod->db->Query($sql);
			}
			echo "<script>parent.location.reload();</script>";
			//$this->show_message('添加成功',  '返回继续添加',        'index.php?app=course&act=timeadd&id='.$id);
		}
	}

	//编辑课程 课时
	function  edit_coursetime(){
		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
		$course_id = isset($_REQUEST['course_id']) ? intval($_REQUEST['course_id']) : 0;
		if (!IS_POST)
		{
			if (!$id)
			{
				$this->show_warning('暂无数据');
				return;
			}
			$sql="select  * from    cw_coursetime where  ct_id=".$id;
			$coursetime=$this->_course_mod->db->getRow($sql);

			if($coursetime['take_time_start']){

				$coursetime['hourstartm']=intval($coursetime['take_time_start'])%60;
				$coursetime['hourstart']=intval($coursetime['take_time_start']/60);
			}
			if($coursetime['take_time_end']){
				$coursetime['hourendm']=$coursetime['take_time_end']%60;
				$coursetime['hourend']=intval($coursetime['take_time_end']/60);
			}
			$h=array();
			for($i=0;$i<24;$i++){
				$h[$i]=$i.'点';
			}
			$this->assign('h', $h);

			$s=array();
			for($i=0;$i<60;$i++){
				$s[$i]=$i.'分';
			}
			$this->assign('s', $s);
			$lessonslist=array();
			for($i=1;$i<=4;$i++){
				$lessonslist[$i]=$i.'课时';
			}

			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js,inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
			$this->assign('lessonslist', $lessonslist);
			$this->assign('course_id', $course_id);
			$coursetime['take_date']=date("Y-m-d",$coursetime['take_date']);
			$this->assign('coursetime', $coursetime);
			$this->display('coursetime.form.html');
		}else{

			$hourstart = !isset($_POST['hourstart']) ? -1 : intval($_POST['hourstart']);
			$hourend = !isset($_POST['hourend']) ? 0 : intval($_POST['hourend']);
			$hourstartm = !isset($_POST['hourstartm']) ? -1 : intval($_POST['hourstartm']);
			$hourendm = !isset($_POST['hourendm']) ? 0 : intval($_POST['hourendm']);
			if($hourstart<0){
				$hourstartm=-1;
			}else{
				if($hourstartm<0){
					$hourstartm=0;
				}
			}
			if($hourend<0){
				$hourendm=-1;
			}else{
				if($hourendm<0){
					$hourendm=0;
				}
			}

			$hourstart=$hourstart*60+$hourstartm;
			$hourend=$hourend*60+$hourendm;
			if($hourend>=0){
				if($hourend<=$hourstart){
					$this->show_warning('时间后者大于前者');
					return;
				}
			}
			$lessons=!isset($_POST['lessons']) ? 0 : intval($_POST['lessons']);
			$note=!isset($_POST['note']) ? '' : trim($_POST['note']);
			$take_date= strtotime($_POST['take_date']);
			$sql="update   cw_coursetime set lessons='$lessons',take_time_start='$hourstart',take_time_end='$hourend' ,take_date='$take_date',note='$note' where ct_id=".$id;
			$this->_course_mod->db->Query($sql);
			//更新课程的课时
			if($course_id){
				$sql="select  *  from  cw_course where  course_id=".$course_id;
				$course=$this->_course_mod->db->GetRow($sql);
				$diff=$course['validity']-$course['validitystart'];
				$days=  $diff/(24*60*60)+1;
				$sql="select  sum(lessons)  from  cw_coursetime where  course_id=".$course_id;
				$lessons=$course=$this->_course_mod->db->Getone($sql);//查询总的课时
				$ls=$days*$lessons;
				$sql="update  cw_course  set lessons='$ls' where  course_id=".$course_id;//更新课程课时

				$this->_course_mod->db->Query($sql);
			}
			echo "<script>parent.location.reload();</script>";
		}
	}


	//删除课时
	function drop_coursetime()
	{
		$ids = isset($_GET['id']) ? trim($_GET['id']) : '';
		$course_id = isset($_GET['course_id']) ? trim($_GET['course_id']) : '';
		if (!$ids)
		{
			$this->show_warning('暂无数据');

			return;
		}
		$ids=explode(',', $ids);
		foreach ($ids as $k=>$v){
			$sql="delete from  cw_coursetime where  ct_id='$v'";
			$this->_course_mod->db->query($sql);
		}
		//更新课程的课时
		if($course_id){
			$sql="select  *  from  cw_course where  course_id=".$course_id;
			$course=$this->_course_mod->db->GetRow($sql);
			$diff=$course['validity']-$course['validitystart'];
			$days=  $diff/(24*60*60)+1;
			$sql="select  sum(lessons)  from  cw_coursetime where  course_id=".$course_id;
			$lessons=$course=$this->_course_mod->db->Getone($sql);//查询总的课时

			$ls=$days*$lessons;
			$sql="update  cw_course  set lessons='$ls' where  course_id=".$course_id;//更新课程课时
			$this->_course_mod->db->Query($sql);
		}
		$this->show_message('删除成功');
	}


	function 	alldel_coursetime(){
		$id = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$id)
		{
			$this->show_warning('暂无数据');
			return;
		}
		if($id){
			$sql="DELETE  from   cw_coursetime where  course_id=".$id;
			$this->_course_mod->db->Query($sql);
		}
		$this->show_message('课时全部清除成功');
	}

	//课时 设置
	function  set_coursetime(){
		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;

		if (!IS_POST)
		{
			if (!$id)
			{
				$this->show_warning('暂无数据');
				return;
			}
			$h=array();
			for($i=0;$i<24;$i++){
				$h[$i]=$i.'点';
			}
			$this->assign('h', $h);
			$s=array();
			for($i=0;$i<60;$i++){
				$s[$i]=$i.'分';
			}
			$this->assign('s', $s);
			$lessonslist=array();
			for($i=1;$i<=4;$i++){
				$lessonslist[$i]=$i.'课时';
			}
			$this->assign('lessonslist', $lessonslist);
			$w=array();
			$arr=array("天","一","二","三","四","五","六");
			for($i=0;$i<=6;$i++){
				$w[$i]='星期'.$arr[$i];
			}
			$this->assign('w', $w);

			$cw=array();
			for($i=1;$i<=52;$i++){
				$cw[$i]=$i.'周';
			}
			$this->assign('cw', $cw);
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js,inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
			$this->display('coursetimeset.form.html');
		}else{

			$hourstart = !isset($_POST['hourstart']) ? -1 : intval($_POST['hourstart']);
			$hourend = !isset($_POST['hourend']) ? 0 : intval($_POST['hourend']);
			$hourstartm = !isset($_POST['hourstartm']) ? -1 : intval($_POST['hourstartm']);
			$hourendm = !isset($_POST['hourendm']) ? 0 : intval($_POST['hourendm']);
			if($hourstart<0){
				$hourstartm=-1;
			}else{
				if($hourstartm<0){
					$hourstartm=0;
				}
			}
			if($hourend<0){
				$hourendm=-1;
			}else{
				if($hourendm<0){
					$hourendm=0;
				}
			}

			$hourstart=$hourstart*60+$hourstartm;
			$hourend=$hourend*60+$hourendm;
			if($hourend>=0){
				if($hourend<=$hourstart){
					$this->show_warning('时间后者大于前者');
					return;
				}
			}
			$w1=date('w', $take_date);
			$w = $w1;
			//isset($_REQUEST['w']) ? intval($_REQUEST['w']) : 0;
			if($w==0){
				$w=7;
			}
			$cw = isset($_REQUEST['cw']) ? intval($_REQUEST['cw']) : 0;//上课周数
			$take_date= strtotime($_POST['take_date']);  //开始日期
			$lessons=isset($_REQUEST['lessons']) ? intval($_REQUEST['lessons']) : 0;
			if($id){

				$sql="select  validitystart,validity,name  from  cw_course where  course_id=".$id;
				$course=$this->_course_mod->db->GetRow($sql);
				$name=$course['name'];
				$validitystart=$course['validitystart'];

				$w2=abs($w-$w1);
				$days=((($validity-$validitystart)/3600/24)) ;
				$s1= $take_date+$w2*3600*24;//开始的第一个时间
				$s2= $take_date+$w2*3600*24;//开始的第一个最后时间

				for ($i = 0; $i <$cw; $i++)
				{
					$take_dates= $s1+$i*3600*24*7;//截止时间
					$sql=" insert  cw_coursetime(lessons,take_time_start,take_time_end,take_date,course_id,note)
					                            values('$lessons','$hourstart','$hourend','$take_dates','$id','$name')";
					$this->_course_mod->db->Query($sql);
				}
				$lessons=$cw*$lessons;
				$sql="update  cw_course set lessons='$lessons' where course_id=".$id;
				$this->_course_mod->db->Query($sql);
				echo "<script>parent.location.reload();</script>";
			}
		}
	}

	// 添加附件
	function  add_coursefile(){
		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
		//	$course_id = isset($_REQUEST['course_id']) ? intval($_REQUEST['course_id']) : 0;
		if (!IS_POST)
		{
			if (!$id)
			{
				$this->show_warning('暂无数据');
				return;
			}
			$file = array('sort_order' => 255,);
			$this->assign('file', $file);
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
			$this->display('coursefile.form.html');
		}else{

			$model_coursefile =& m('coursefile');
			$data = array();
			$data['sort_order']= isset($_REQUEST['sort_order']) ? intval($_REQUEST['sort_order']) : 0;
			$data['add_time']=gmtime();
			$data['course_id']=$id;
			$file_id=$model_coursefile->add($data);
			if (!$file_id )
			{
				$this->show_warning($model_coursefile->get_error());
				return;
			}
			$names=$_FILES["name"]['name'];
			$names=explode('.', $names);
			$name=$names[0];
			$types=$_FILES["name"]['type'];
			$types=explode('/', $types);
			$type=$types[1];
			if($type=='mp4'){
				$type='video';
			}
			$size=$_FILES["name"]['size'];
			$image_files=$_FILES['name'];//上传文件

			if($image_files['name']){
				$Cfile       =   $this->_upload_couresefile($file_id,$id);
				if($type=='pdf'){
					$pic=$this->pdftoimg($Cfile,$file_id);
				}else{ // mp4格式
					if(!strpos($image_files['name'],'pdf')){
						if(extension_loaded('ffmpeg')){//判断ffmpeg是否载入
							$mov = new ffmpeg_movie(ROOT_PATH.'/'.$Cfile);//视频的路径
							if($mov){
								$ff_frame = $mov->getFrame(5);
								if($ff_frame)
								{
									$gd_image = $ff_frame->toGDImage();
									$pic="/data/files/mall/coursefile/movie/".time().".jpg";//要生成图片的绝对路径
									imagejpeg($gd_image, ROOT_PATH.'/'.$pic);//创建jpg图像
									imagedestroy($gd_image);//销毁一图像
								}
							}
						}
					}
				}
			}
			if($_FILES["pic"]['name']){
				if($type=='pdf'){
					$pic       =   $this->_upload_couresefilefengmian($file_id,$file_id);
				}elseif ($type=='video'){
					$pic       =   $this->_upload_couresefilefengmian($file_id,'movie');
				}
			}

			if($Cfile){
				$data=array();
				$data['name']=$name;
				$data['size']=$size;
				$data['path']=$Cfile;
				$data['pic']=$pic;
				$data['type']=$type;
				$model_coursefile->edit($file_id,$data);
				echo "<script>parent.location.reload();</script>";
			}else{
				$this->show_warning('添加失败');
				echo "<script>parent.location.reload();</script>";
			}

		}
	}
	function  edit_coursefile(){
		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
		$course_id = isset($_REQUEST['course_id']) ? intval($_REQUEST['course_id']) : 0;
		$model_coursefile =& m('coursefile');
		if (!IS_POST)
		{
			if (!$id)
			{
				$this->show_warning('暂无数据');
				return;
			}
			$coursefile= $model_coursefile->find($id);
			$coursefile    =   current($coursefile);
			$coursefile['add_time']=	 date('y-m-d H:s:m',$coursefile['add_time']);
			$this->assign('file', $coursefile);
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,change_upload.js'));
			$this->display('coursefile.form.html');
		}else{

			$model_coursefile =& m('coursefile');
			$data = array();
			$data['sort_order']= isset($_REQUEST['sort_order']) ? intval($_REQUEST['sort_order']) : 0;
			$data['add_time']=gmtime();
			$data['course_id']=$course_id;
			$file_id=$model_coursefile->edit($id,$data);

			$names=$_FILES["name"]['name'];
			if($names){
				$names=explode('.', $names);
				$name=$names[0];
				$types=$_FILES["name"]['type'];
				$types=explode('/', $types);
				$type=$types[1];
				if($type=='mp4'){
					$type='video';
				}
			}
			$size=$_FILES["name"]['size'];
			$image_files=$_FILES['name'];//上传文件
			if($image_files['name']){
				$Cfile       =   $this->_upload_couresefile($file_id,$id);
				if($type=='pdf'){
					$pic=$this->pdftoimg($Cfile,$id);
				}else{ // mp4格式
					if(!strpos($image_files['name'],'pdf')){
						if(extension_loaded('ffmpeg')){//判断ffmpeg是否载入
							$mov = new ffmpeg_movie(ROOT_PATH.'/'.$Cfile);//视频的路径
							if($mov){
								$ff_frame = $mov->getFrame(10);
								if($ff_frame)
								{
									$gd_image = $ff_frame->toGDImage();
									$pic="/data/files/mall/coursefile/movie/".time().".jpg";//要生成图片的绝对路径
									imagejpeg($gd_image, ROOT_PATH.'/'.$pic);//创建jpg图像
									imagedestroy($gd_image);//销毁一图像
								}
							}
						}
					}
				}
			}

			if($_FILES["pic"]['name']){
				$pic       =   $this->_upload_couresefilefengmian($id,'cover');

			}
			$data['pic']=$pic;

			if($Cfile){
				$data=array();
				$data['name']=$name;
				$data['size']=$size;
				$data['path']=$Cfile;
				$data['pic']=$pic;
				$data['type']=$type;
			}
			$model_coursefile->edit($id,$data);
			echo "<script>parent.location.reload();</script>";
		}
	}


	//删除附件
	function  drop_coursefile(){
		$article_ids = isset($_GET['id']) ? trim($_GET['id']) : '';
		if (!$article_ids)
		{
			$this->show_warning('no_such_activity');
			return;
		}
		$article_ids=explode(',', $article_ids);
		$model_coursefile =& m('coursefile');
		$model_coursefile->drop($article_ids);
		if ($model_coursefile->has_error())    //删除
		{
			$this->show_warning($model_coursefile->get_error());
			return;
		}
		$this->show_message('drop_ok');
	}

	function _upload_logo($brand_id)
	{
		$file = $_FILES['pic'];
		if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
		{
			return '';
		}
		import('uploader.lib');             //导入上传类
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
		$uploader->addFile($_FILES['pic']);//上传logo

		if (!$uploader->file_info())
		{
			$this->show_warning($uploader->get_error() , 'go_back', 'index.php?app=activity&amp;act=course&amp;id=' . $brand_id);
			return false;
		}
		// 指定保存位置的根目录
		$uploader->root_dir(ROOT_PATH);
		$imgname=gmtime();
		// 上传
		if ($file_path = $uploader->save('data/files/mall/course', $imgname))   //保存到指定目录，并以指定文件名$brand_id存储
		{
			return $file_path;
		}
		else
		{
			return false;
		}
	}

	function _upload_couresefile($brand_id,$course_id)
	{

		$file = $_FILES['name'];
		if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
		{
			return '';
		}
		import('uploader.lib');             //导入上传类
		$uploader = new Uploader();
		$uploader->allowed_type(COURSW_FILE_TYPE); //限制文件类型
		$uploader->addFile($_FILES['name']);//上传logo

		if (!$uploader->file_info())
		{
			//$this->show_warning($uploader->get_error() , 'go_back', 'index.php?app=course&amp;act=edit&amp;id=' . $course_id);
			//	echo "<script>parent.location.reload();</script>";
			return false;
		}
		// 指定保存位置的根目录
		$uploader->root_dir(ROOT_PATH);
		$imgname=md5(gmtime());
		// 上传
		if ($file_path = $uploader->save('/data/files/mall/coursefile', $imgname))   //保存到指定目录，并以指定文件名$brand_id存储
		{
			return $file_path;
		}
		else
		{
			return false;
		}
	}


	function _upload_couresefilefengmian($brand_id,$ptah)
	{

		$file = $_FILES['pic'];
		if ($file['error'] == UPLOAD_ERR_NO_FILE) // 没有文件被上传
		{
			return '';
		}
		import('uploader.lib');             //导入上传类
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE); //限制文件类型
		$uploader->addFile($_FILES['pic']);//上传logo

		if (!$uploader->file_info())
		{
			//$this->show_warning($uploader->get_error() , 'go_back', 'index.php?app=course&amp;act=edit&amp;id=' . $course_id);
			//	echo "<script>parent.location.reload();</script>";
			return false;
		}
		// 指定保存位置的根目录
		$uploader->root_dir(ROOT_PATH);
		$imgname=md5(gmtime());
		// 上传

		if($ptah){
			$file_path= $uploader->save('/data/files/mall/coursefile/'.$ptah, $imgname);
		}else {
			$file_path= $uploader->save('/data/files/mall/coursefile/', $imgname);
		}

		if ($file_path )   //保存到指定目录，并以指定文件名$brand_id存储
		{
			return $file_path;
		}
		else
		{
			return false;
		}
	}


	//PDF 格式上传
	function pdftoimg($file,$id){
		if($id){
			$pdf=ROOT_PATH.$file;
			$picfile=md5(time());
			$pic='/data/files/mall/coursefile/'.$id.'/';

			if (!file_exists(ROOT_PATH.$pic))
			{
				if (!mkdir(ROOT_PATH.$pic))
				{
					$this->show_warning("创建目录失败",1);
					exit();
				}
			}else{
				$dh=opendir(ROOT_PATH.$pic);
				while ($file=readdir($dh)) {
					if($file!="." && $file!="..") {
						$fullpath=ROOT_PATH.$pic."/".$file;
						if(!is_dir($fullpath)) {
							unlink($fullpath);
						}
					}
				}
			}
			$file = fopen("test.txt","w");
			fwrite($file,"gswin32c -q -dSAFER -dBATCH -dNOPAUSE -r300 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sDEVICE=jpeg -sOutputFile=".ROOT_PATH.$pic.$picfile."_%d.jpg -dFirstPage=1 $pdf");
			$file=true;
			exec("gswin32c -q -dSAFER -dBATCH -dNOPAUSE -r300 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sDEVICE=jpeg -sOutputFile=".ROOT_PATH.$pic.$picfile."_%d.jpg -dFirstPage=1 $pdf");

			if($_POST['turn']){
				$dh=opendir(ROOT_PATH.$pic);

				while ($file=readdir($dh)) {
					if($file!="." && $file!="..") {
						$fullpath=ROOT_PATH.$pic.$file;
						if(!is_dir($fullpath)) {
							if(strpos($file, '_1.jpg')){
								@copy($fullpath, ROOT_PATH.$pic.$picfile.'_cover.jpg');
							}
							if(!strpos($file, '_cover.jpg')){
								$this->flip($fullpath);
							}
						}
					}
				}
			}else{
				@copy(ROOT_PATH.$pic.$picfile.'_1.jpg', ROOT_PATH.$pic.$picfile.'_cover.jpg');
			}
			return $pic.$picfile.'_cover.jpg';
		}else{
			return "";
		}
	}

	function flip($filename,$degrees = 90){
		//读取图片
		$data = @getimagesize($filename);
		if($data==false)return false;
		//读取旧图片
		switch ($data[2]) {
			case 1:
				$src_f = imagecreatefromgif($filename);break;
			case 2:
				$src_f = imagecreatefromjpeg($filename);break;
			case 3:
				$src_f = imagecreatefrompng($filename);break;
		}
		if($src_f=="")return false;
		$rotate = @imagerotate($src_f, $degrees,0);
		if(!imagejpeg($rotate,$filename,100))return false;
		@imagedestroy($rotate);
		return true;
	}


	function upload_file($upload, $dir = '', $file_name = '')
	{
		/* 没有指定目录默认为根目录images */
		if (empty($dir))
		{
			/* 创建当月目录 */
			$dir = date('Ym');
			$dir = ROOT_PATH . 'data/files/mall/couresefile/' . $dir . '/';
		}
		else
		{
			/* 创建目录 */
			$dir = ROOT_PATH . 'data/files/mall/couresefile/' . $dir . '/';
			if ($file_name)
			{
				$file_name = $dir . $file_name; // 将图片定位到正确地址
			}
		}

		/* 如果目标目录不存在，则创建它 */
		if (!file_exists($dir))
		{
			if (!make_dir($dir))
			{
				/* 创建目录失败 */
				sys_msg("创建目录失败",1);
				exit();
			}
		}

		if (empty($file_name))
		{
			$file_name = $dir . gmtime() . get_filetype($upload['name']);
		}

		/* 允许上传的文件类型 */
		$allow_file_types = '|MP4|PDF|';

		if (!check_file_type($upload['tmp_name'], $file_name, $allow_file_types))
		{
			sys_msg("不支持的文件格式",1);
			exit();
		}

		if (move_file($upload, $file_name))
		{
			return str_replace(ROOT_PATH, '', $file_name);
		}
		else
		{
			sys_msg(sprintf($GLOBALS['_LANG']['upload_failure'], $upload['name']));
			sys_msg(ERR_UPLOAD_FAILURE);

			return false;
		}
	}

}

?>